package com.kj.misc.service;

import java.util.List;
import java.util.Optional;

import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.kj.misc.domain.MiscConfig;
import com.kj.misc.domain.MiscFetcherConfig;
import com.kj.misc.domain.MiscFetcherConfig.FetcherEntry;
import com.kj.misc.domain.MiscStoreType;

@Component
public class MiscFetcherManager {
	
	private List<MiscFetcher> fetchers = Lists.newLinkedList();
	
	@Autowired
	private MiscData data;
	
	@PreDestroy
	public void terminate() {
		
		stop();
		
	}
	
	public void start() {
		
		MiscConfig config = MiscConfig.instance.get();
		config.getFetcherConfig().getFetchers().forEach(fe->{
			
			fe.getValues().forEach(ve->{
				data.registerData(MiscFetcherConfig.key(fe, ve), MiscStoreType.period);
			});
			
			startFetcher(fe);
			
		});
	}
	
	public void stop() {
		
		// stop all fetcher	
		fetchers.stream().forEach(MiscFetcher::stop);
		
		// clear the list
		fetchers.clear();
		
	}
	
	public List<MiscFetcher> fetchers() {
		return Lists.newLinkedList(fetchers);
	}
	
	public void dispatch(String key, double value) {
		data.update(key, value);		
	}
	
	public Optional<MiscFetcher> getFetcherByName(String name) {
		return fetchers.stream().filter(f->f.getContext().getName().equals(name)).findFirst();
	}
	
	private MiscFetcher startFetcher(FetcherEntry fe) {
		// build fetcher
		MiscFetcher fetcher = new MiscFetcher(this, fe);
		fetcher.start();
		fetchers.add(fetcher);
		return fetcher;
	}
	
	public void removeFetcher(String name) {
		fetchers.stream()
			.filter(f->f.getContext().getName().equals(name))
			.forEach(f->f.stop());
		fetchers.removeIf(f->f.getContext().getName().equals(name));
	}
	
	public Optional<String> getParameter(String valuekey, String parameterKey) {
		
		MiscConfig config = MiscConfig.instance.get();
		
		return config.getFetcherConfig().getParameter(valuekey, parameterKey);
		
	}
	
	public boolean updateParameter(String valuekey, String parameterKey, String parameterValue) {
		
		MiscConfig config = MiscConfig.instance.get();
		
		boolean ret =  config.getFetcherConfig().updateParameter(valuekey, parameterKey, parameterValue);
		
		if(ret) {
			
			MiscConfig.instance.set();
			
		}
		
		return ret;
		
	}

}
